package com.bskj.kuaifu.nettyService.service.handler;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.constants.CommonConstatns;
import com.bskj.common.utils.EncryptUtil;
import com.bskj.common.utils.HttpClientUtils;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.StringUtils;
import com.bskj.kuaifu.nettyService.protobuf.Utils;
import com.bskj.kuaifu.nettyService.protobuf.generate.cli2srv.register.Register;
import com.bskj.kuaifu.nettyService.service.utils.ClientConnection;
import com.bskj.kuaifu.nettyService.service.utils.ClientConnectionMap;
import com.google.protobuf.Message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by Dell on 2016/2/18.
 */

public class LogicServerHandler extends SimpleChannelInboundHandler<Message> {
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		LogUtils.info("连接来了 ======================== " );
		//保存客服端连接
		ClientConnectionMap.addClientConnection(ctx);
		ClientConnectionMap.logAllCollection();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		//移除客服端连接
		ClientConnectionMap.removeClientConnection(ctx);
		ClientConnectionMap.logAllCollection();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
		LogUtils.info("注册/登录信息 ======================== " );
		LogUtils.info(message);
		
		ClientConnectionMap.logAllCollection();
		
		//客服端向服务端只会发送身份验证信息（注册/登录信息）
		Register.Resquest request = (Register.Resquest) message;
		String boxNo = request.getBoxNo(); //岗亭编号
		String boxName = request.getBoxName(); //岗亭描述
		long id = request.getId(); // 车场ID
		String uuid = request.getUuid(); //车场UUID 
		String rails = request.getRails(); //车场抬杆信息

		ClientConnection clientConnection = ClientConnectionMap.getClientConnection(id + "_" + boxNo);
		com.bskj.kuaifu.nettyService.protobuf.generate.server2cli.register.Register.Resp.Builder cb = com.bskj.kuaifu.nettyService.protobuf.generate.server2cli.register.Register.Resp
				.newBuilder();
		if (clientConnection != null) {
			cb.setCode("400");
			cb.setMsg("该岗亭已经登录！");
		} else {
			if (StringUtils.isBank(rails) && StringUtils.isBank(boxName)) {
				//登录
				cb.setCode("200");
				cb.setMsg("登录成功！");
				ClientConnectionMap.register(ctx, id + "_" + boxNo);
			} else {
				//注册
				String registerUrl = "https://kuaifu.boshukeji.com/action/do";
				JSONObject paramObj = new JSONObject();
				paramObj.put("uri", "/noCarnoParkInfo/register");
				paramObj.put("boxNo", boxNo);
				paramObj.put("boxName", boxName);
				paramObj.put("parkLotId", id);
				paramObj.put("parkLotUuid", uuid);
				paramObj.put("rails", rails);
				String paramsStr = EncryptUtil.encrypt(paramObj.toJSONString(), CommonConstatns.AES_KEY);
				Map<String, String> params = new HashMap<>();
				params.put("params", paramsStr);
				String responeStr = HttpClientUtils.postRequest(registerUrl, params);
				boolean result;
				try {
					JSONObject responeObj = (JSONObject)JSONObject.parse(responeStr);
					result = (boolean) responeObj.get("result");
					if (result) {
						cb.setCode("200");
						cb.setMsg("注册成功！");
						ClientConnectionMap.register(ctx, id + "_" + boxNo);
					} else {
						cb.setCode("400");
						cb.setMsg("注册信息有误！");
					}
				} catch (Exception e) {
					cb.setCode("400");
					cb.setMsg("注册信息有误！");
				}
			}

		}
		ByteBuf byteBuf = Utils.pack2Client(cb.build());
		ctx.writeAndFlush(byteBuf);
	}
}
